package entityAdapter

import (
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commConfig"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntityManager"
	"gitee.com/fierce_wolf/go-fox-edge-common/commSql"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Number"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"time"
)

type deviceValueRecordAdapter struct {
	lastTime int64
}

func (e *deviceValueRecordAdapter) SaveDeviceValueRecord(valueEntityList []*edgeEntity.DeviceValueEntity) {
	// 定义一个最终的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
		}
	}()

	// 检查：数据的有效性
	if len(valueEntityList) == 0 {
		return
	}

	// 检查：是否需要记录
	configs, err := commConfig.GetConfigParam("serverConfig")
	if err != nil {
		return
	}
	deviceHistory := Map.GetMap(configs, "deviceValueRecord", make(map[string]interface{}))
	if !Map.GetBool(deviceHistory, "enable", false) {
		return
	}

	// 从第一个元素中，取得设备厂商、型号、名称信息
	valueEntity := valueEntityList[0]

	deviceValueRecordEntity := edgeEntity.Type.DeviceValueRecordEntity.Instance()
	deviceValueRecordEntity.Manufacturer = valueEntity.Manufacturer
	deviceValueRecordEntity.DeviceType = valueEntity.DeviceType
	deviceValueRecordEntity.DeviceName = valueEntity.DeviceName

	for _, valueEntity = range valueEntityList {
		value := make(map[string]interface{})
		for key, val := range valueEntity.Params {
			data := make(map[string]interface{})
			data["value"] = val.Value
			data["time"] = val.Time

			value[key] = data
		}

		deviceValueRecordEntity.DeviceValues = append(deviceValueRecordEntity.DeviceValues, value)
	}

	// 保存历史记录
	commSql.InsertEntity(deviceValueRecordEntity)
}

func (e *deviceValueRecordAdapter) ClearDeviceValueRecordEntity() {
	// 定义一个最终的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
		}
	}()

	if !commEntityManager.EntityManager.Initialized {
		return
	}

	configs, err := commConfig.GetConfigParam("serverConfig")
	if err != nil {
		return
	}

	value := Map.GetOrDefault(configs, "deviceValueRecord", make(map[string]interface{}))
	params := value.(map[string]interface{})

	maxCount := Number.MakeInt64(Map.GetOrDefault(params, "maxCount", 1000000))
	period := Number.MakeInt64(Map.GetOrDefault(params, "period", 3600))

	// 检查：执行周期是否到达
	currentTime := time.Now().UnixMilli()
	if (currentTime - e.lastTime) < period*1000 {
		return
	}
	e.lastTime = currentTime

	// 除了最近的maxCount条数据，旧数据全部删除
	e.deleteDeviceValueRecord(maxCount)
}

func (e *deviceValueRecordAdapter) deleteDeviceValueRecord(retainCount int64) {
	// 查询记录数量
	sumCount, err := commSql.Client.QueryCount("SELECT COUNT(1) FROM  tb_device_value_record")
	if err != nil {
		return
	}
	if int64(sumCount) <= retainCount {
		return
	}

	// 执行SQL删除语句
	sql := fmt.Sprintf("DELETE FROM tb_device_value_record WHERE id NOT IN (SELECT t1.id AS id FROM (SELECT t.id FROM tb_device_value_record t ORDER BY t.id LIMIT %v) t1)", retainCount)
	commSql.Client.Exec(sql, nil)

	// 累计删除数量
	VacuumAdapter.Accumulate(int64(sumCount) - retainCount)
	VacuumAdapter.Vacuum()
}
